let formidable = require('formidable');
let path = require('path');
// 引入表结构
let Product = require('../../db/productSchame');
let form = formidable({
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../', '../', 'public', 'uploads')
});

module.exports = (req, res) => {
    form.parse(req, async(err, fields, files) => {
        // 除了file文件里的图片内容,其余的内容都可以在fields
        console.log(fields);
        // file文件上传的内容
        console.log(files);
        if (err) {
            res.status(500).send(err);
        } else {
            // 如果不修改文件图片,那么当前数据库不再修改文件内容
            if (!files.pic.originalFilename) {
                await Product.updateOne({ "_id": req.params.id }, {
                    title: fields.title,
                    cate_id: fields.cate_id,
                    goods_id: fields.goods_id,
                    price: fields.price,
                    fee: fields.fee,
                    description: fields.description
                });
            } else {
                await Product.updateOne({ "_id": req.params.id }, {
                    title: fields.title,
                    cate_id: fields.cate_id,
                    goods_id: fields.goods_id,
                    price: fields.price,
                    fee: fields.fee,
                    description: fields.description,
                    pic: files.pic.filepath.split('public')[1],
                });
            };
            try {
                res.redirect('/product/productlist');
            } catch (error) {
                res.status(500).send('修改失败')
            };
        }
    });

}